{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 协同过滤数据准备\n",
    "\n",
    "对训练数据，\n",
    "1. 建立用户和物品索引，方便用下标访问打分表\n",
    "2. 建立倒排表，加速查询访问\n",
    "3. 打分表按用户、物品索引保存为稀疏矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "#导入工具包\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "#字典，用于建立用户和物品的索引\n",
    "from collections import defaultdict\n",
    "\n",
    "#稀疏矩阵，存储打分表\n",
    "import scipy.io as sio\n",
    "import scipy.sparse as ss\n",
    "\n",
    "#数据到文件存储\n",
    "import pickle"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>user_id</th>\n",
       "      <th>item_id</th>\n",
       "      <th>rating</th>\n",
       "      <th>timestamp</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>5</td>\n",
       "      <td>874965758</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>876893171</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>4</td>\n",
       "      <td>878542960</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>4</td>\n",
       "      <td>3</td>\n",
       "      <td>876893119</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>5</td>\n",
       "      <td>3</td>\n",
       "      <td>889751712</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   user_id  item_id  rating  timestamp\n",
       "0        1        1       5  874965758\n",
       "1        1        2       3  876893171\n",
       "2        1        3       4  878542960\n",
       "3        1        4       3  876893119\n",
       "4        1        5       3  889751712"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#读取训练数据\n",
    "triplet_cols = ['user_id','item_id', 'rating', 'timestamp'] \n",
    "\n",
    "dpath = './data/'\n",
    "df_triplet = pd.read_csv(dpath +'u1.base', sep='\\t', names=triplet_cols, encoding='latin-1')\n",
    "df_triplet.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n",
      "<class 'numpy.ndarray'>\n",
      "n_users: 943\n",
      "n_items: 1650\n"
     ]
    }
   ],
   "source": [
    "#统计总的用户数目和物品数目\n",
    "unique_users = df_triplet['user_id'].unique()\n",
    "unique_items = df_triplet['item_id'].unique()\n",
    "print(type(unique_users))\n",
    "print(type(unique_items))\n",
    "n_users = unique_users.shape[0]\n",
    "n_items = unique_items.shape[0]\n",
    "print(\"n_users:\",(n_users))\n",
    "print(\"n_items:\",(n_items))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "#建立用户和物品的索引表\n",
    "#本数据集中user_id和item_id都已经是索引了,可以减1，将从1开始编码变成从0开始的编码\n",
    "#下面的代码更通用，可对任意编码的用户和物品重新索引\n",
    "users_index = dict()\n",
    "items_index = dict()\n",
    "\n",
    "for j, u in enumerate(unique_users):\n",
    "    users_index[u] = j\n",
    "    \n",
    "#重新编码活动索引字典    \n",
    "for j, i in enumerate(unique_items):\n",
    "    items_index[i] = j\n",
    "    \n",
    "#保存用户索引表\n",
    "pickle.dump(users_index, open(\"users_index.pkl\", 'wb'))\n",
    "#保存活动索引表\n",
    "pickle.dump(items_index, open(\"items_index.pkl\", 'wb'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'collections.defaultdict'>\n"
     ]
    }
   ],
   "source": [
    "#倒排表\n",
    "#统计每个用户打过分的电影   / 每个电影被哪些用户打过分\n",
    "user_items = defaultdict(set)\n",
    "item_users = defaultdict(set)\n",
    "print(type(user_items))\n",
    "#用户-物品关系矩阵R, 稀疏矩阵，记录用户对每个电影的打分\n",
    "user_item_scores = ss.dok_matrix((n_users, n_items))\n",
    "\n",
    "#扫描训练数据\n",
    "for line in df_triplet.index:  #对每条记录\n",
    "    cur_user_index = users_index [df_triplet.iloc[line]['user_id']]\n",
    "    cur_item_index = items_index [df_triplet.iloc[line]['item_id']]\n",
    "    \n",
    "    #倒排表, 存放转换后的索引\n",
    "    user_items[cur_user_index].add(cur_item_index)    #该用户对这个电影进行了打分\n",
    "    item_users[cur_item_index].add(cur_user_index)    #该电影被该用户打分\n",
    "\n",
    "    user_item_scores[cur_user_index, cur_item_index] = df_triplet.iloc[line]['rating']\n",
    "\n",
    "\n",
    "##保存倒排表\n",
    "#每个用户打分的电影\n",
    "pickle.dump(user_items, open(\"user_items.pkl\", 'wb'))\n",
    "##对每个电影打过分的用户\n",
    "pickle.dump(item_users, open(\"item_users.pkl\", 'wb'))\n",
    "\n",
    "#保存打分矩阵，在UserCF和ItemCF中用到\n",
    "sio.mmwrite(\"user_item_scores\", user_item_scores)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
